package core.base.exception;

import java.util.Locale;
import java.util.Map;

import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;

public class AppExceptionMessageServiceImpl implements AppExceptionMessageService {

	private MessageSource messageSource;

	private Map<String, AppExceptionMessageService> appExceptionMessageServices;

	private AppExceptionMessageService getAppExceptionMessageService(String code) {
		if (appExceptionMessageServices == null) {
			return null;
		}

		return appExceptionMessageServices.get(code);
	}

	private String getTextMessage(String code, Object[] args) {
		try {
			return messageSource.getMessage(code, args, Locale.SIMPLIFIED_CHINESE);
		} catch (NoSuchMessageException e) {
			return e.getMessage();
		}
	}

	public void processMessage(AppBizException abe) {
		AppExceptionMessageService aems = getAppExceptionMessageService(abe.getCode());
		if (aems != null) {
			aems.processMessage(abe);
			return;
		}

		String txtMsg = getTextMessage(abe.getCode(), abe.getArgs());
		abe.setTextMessage(txtMsg);
	}

	public void processMessage(AppRTException are) {
		AppExceptionMessageService aems = getAppExceptionMessageService(are.getCode());
		if (aems != null) {
			aems.processMessage(are);
			return;
		}

		String txtMsg = getTextMessage(are.getCode(), are.getArgs());
		are.setTextMessage(txtMsg);
	}

	public MessageSource getMessageSource() {
		return messageSource;
	}

	public void setMessageSource(MessageSource messageSource) {
		this.messageSource = messageSource;
	}

	public Map<String, AppExceptionMessageService> getAppExceptionMessageServices() {
		return appExceptionMessageServices;
	}

	public void setAppExceptionMessageServices(Map<String, AppExceptionMessageService> appExceptionMessageServices) {
		this.appExceptionMessageServices = appExceptionMessageServices;
	}

}
